<template>
  <div class="word-book">
    <!-- 顶部栏 -->
    <div class="word-book__header">
      <div class="header-left">
        <h2 class="word-book__title">单词本</h2>
        <!-- 教材选择器 -->
        <el-select
          v-model="selectedProgramId"
          placeholder="选择教材"
          style="width: 200px"
          @change="onProgramChange"
        >
          <el-option
            v-for="program in localProgramList"
            :key="program.id"
            :label="program.nameZhCn"
            :value="program.id"
          />
        </el-select>

        <!-- 单元选择器 -->
        <el-select
          v-model="selectedUnitId"
          placeholder="选择单元"
          style="width: 200px"
          :disabled="!selectedProgramId"
          @change="onUnitChange"
        >
          <el-option
            v-for="unit in localUnitList"
            :key="unit.id"
            :label="unit.nameZhCn"
            :value="unit.id"
          />
        </el-select>
      </div>

      <!-- 显示控制按钮 -->
      <div class="header-right">
        <el-button-group>
          <el-button
            :type="globalDisplayState.showSpelling ? 'primary' : 'default'"
            @click="toggleGlobalSpelling"
          >
            {{ globalDisplayState.showSpelling ? '隐藏拼写' : '显示拼写' }}
          </el-button>
          <el-button
            :type="globalDisplayState.showMeaning ? 'primary' : 'default'"
            @click="toggleGlobalMeaning"
          >
            {{ globalDisplayState.showMeaning ? '隐藏词义' : '显示词义' }}
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 内容区域 -->
    <div v-loading="loading" class="word-book__content">
      <el-table
        :data="localWordList"
        style="width: 100%"
        :stripe="true"
        class="word-table"
      >
        <!-- 序号列 -->
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ row }">
            <span class="word-index">{{ row.wordIndex }}</span>
          </template>
        </el-table-column>

        <!-- 音标/读音列 -->
        <el-table-column label="音标/读音" width="200">
          <template #default="{ row }">
            <div class="syllable-cell">
              <span class="syllable-text">{{ row.syllable }}</span>
              <el-button
                type="primary"
                link
                :icon="VideoPlay"
                @click="playAudio(row.spelling)"
                class="play-button"
              >
                播放
              </el-button>
            </div>
          </template>
        </el-table-column>

        <!-- 单词拼写列 -->
        <el-table-column label="单词拼写" width="250">
          <template #default="{ row, $index }">
            <div class="spelling-cell" @click="toggleSpelling($index)">
              <span
                v-if="wordDisplayStates[$index]?.showSpelling"
                class="spelling-text"
              >
                {{ row.spelling }}
              </span>
              <span v-else class="spelling-hidden">点击显示拼写</span>
              <el-button type="primary" link size="small" class="toggle-button">
                {{ wordDisplayStates[$index]?.showSpelling ? '隐藏' : '显示' }}
              </el-button>
            </div>
          </template>
        </el-table-column>

        <!-- 词义列 -->
        <el-table-column label="词义">
          <template #default="{ row, $index }">
            <div class="meaning-cell" @click="toggleMeaning($index)">
              <div
                v-if="wordDisplayStates[$index]?.showMeaning"
                class="meaning-content"
              >
                <div class="meaning-text">{{ row.meaningZhCn }}</div>
                <div v-if="row.exampleEnUs" class="example-text">
                  <div class="example-en">{{ row.exampleEnUs }}</div>
                  <div v-if="row.exampleZhCn" class="example-zh">
                    {{ row.exampleZhCn }}
                  </div>
                </div>
              </div>
              <span v-else class="meaning-hidden">点击显示词义</span>
              <el-button type="primary" link size="small" class="toggle-button">
                {{ wordDisplayStates[$index]?.showMeaning ? '隐藏' : '显示' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <Pagination
          v-model:page="pagination.pageNum"
          v-model:limit="pagination.pageSize"
          :total="wordTotal"
          @pagination="fetchWordList"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import { useDcyxWordBookStoreHook, useDcyxProgramStoreHook, useDcyxUnitStoreHook } from '@/store'
import type {
  WordBookItem,
  ProgramItem,
  UnitItem,
  WordDisplayState,
} from '@/api/dcyx/word-book.api'

defineOptions({
  name: 'WordBook',
  inheritAttrs: false,
})

const wordBookStore = useDcyxWordBookStoreHook()
const programStore = useDcyxProgramStoreHook()
const unitStore = useDcyxUnitStoreHook()

// 响应式数据
const selectedProgramId = ref<number>(0)
const selectedUnitId = ref<number>(0)
const loading = ref(false)

// 本地数据
const localWordList = ref<WordBookItem[]>([])
const localProgramList = ref<ProgramItem[]>([])
const localUnitList = ref<UnitItem[]>([])

// 分页数据
const pagination = ref({
  pageNum: 1,
  pageSize: 20,
})

// 全局显示状态
const globalDisplayState = ref<WordDisplayState>({
  showSpelling: false,
  showMeaning: false,
})

// 每个单词的显示状态
const wordDisplayStates = ref<Record<number, WordDisplayState>>({})

// 计算属性
const wordTotal = computed(() => wordBookStore.wordTotal)

// 获取单词列表
async function fetchWordList() {
  if (!selectedProgramId.value) return

  try {
    loading.value = true
    const list = await wordBookStore.fetchWordList({
      programId: selectedProgramId.value,
      unitId: selectedUnitId.value || undefined,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
    })
    localWordList.value = list

    // 初始化每个单词的显示状态
    initWordDisplayStates()
  } catch (error) {
    console.error('获取单词列表失败:', error)
    ElMessage.error('获取单词列表失败')
  } finally {
    loading.value = false
  }
}

// 获取教材列表
async function fetchProgramList() {
  try {
    const currentSeriesId = programStore.currentSeriesId
    if (!currentSeriesId) {
      console.warn('当前系列ID不存在，等待初始化完成')
      return
    }

    console.log('获取教材列表, seriesId:', currentSeriesId)
    const list = await wordBookStore.fetchProgramList({
      seriesId: currentSeriesId,
      pageNum: 1,
      pageSize: 50,
    })
    localProgramList.value = list
    console.log('获取教材列表成功, 数量:', list.length)

    // 设置默认选中的教材
    if (list.length > 0 && !selectedProgramId.value) {
      selectedProgramId.value = programStore.currentProgramId || list[0].id
      console.log('设置默认选中教材:', selectedProgramId.value)
    }
  } catch (error) {
    console.error('获取教材列表失败:', error)
    ElMessage.error('获取教材列表失败')
  }
}

// 获取单元列表
async function fetchUnitList() {
  if (!selectedProgramId.value) return

  try {
    const list = await wordBookStore.fetchUnitList({
      programId: selectedProgramId.value,
      pageNum: 1,
      pageSize: 100,
    })
    localUnitList.value = list
    // 重置单元选择
    selectedUnitId.value = localUnitList.value[0].id
  } catch (error) {
    console.error('获取单元列表失败:', error)
    ElMessage.error('获取单元列表失败')
  }
}

// 教材切换
async function onProgramChange() {
  pagination.value.pageNum = 1
  selectedUnitId.value = 0
  await fetchUnitList()
  fetchWordList()
}

// 单元切换
function onUnitChange() {
  pagination.value.pageNum = 1
  fetchWordList()
}

// 播放单词音频
// async function playAudio(word: string) {
//   try {
//     await wordBookStore.playWordAudio(word)
//   } catch (error) {
//     console.error('播放音频失败:', error)
//     ElMessage.error('播放音频失败')
//   }
// }

// 播放单词发音
async function playAudio(word: string) {
  // const word = currentWord.value?.spelling
  if (!word) return
  if ((window as any).wordAudio) {
    ;(window as any).wordAudio.pause()
    ;(window as any).wordAudio.currentTime = 0
  }
  const audioUrl = await wordBookStore.playWordAudio(word)
  ;(window as any).wordAudio = new window.Audio(audioUrl)
  ;((window as any).wordAudio as HTMLAudioElement).play()
}

// 初始化单词显示状态
function initWordDisplayStates() {
  const states: Record<number, WordDisplayState> = {}
  localWordList.value.forEach((_, index) => {
    states[index] = {
      showSpelling: globalDisplayState.value.showSpelling,
      showMeaning: globalDisplayState.value.showMeaning,
    }
  })
  wordDisplayStates.value = states
}

// 切换单个单词拼写显示
function toggleSpelling(index: number) {
  if (wordDisplayStates.value[index]) {
    wordDisplayStates.value[index].showSpelling =
      !wordDisplayStates.value[index].showSpelling
  }
}

// 切换单个单词词义显示
function toggleMeaning(index: number) {
  if (wordDisplayStates.value[index]) {
    wordDisplayStates.value[index].showMeaning =
      !wordDisplayStates.value[index].showMeaning
  }
}

// 全局切换拼写显示
function toggleGlobalSpelling() {
  globalDisplayState.value.showSpelling = !globalDisplayState.value.showSpelling
  Object.keys(wordDisplayStates.value).forEach((key) => {
    const index = parseInt(key)
    wordDisplayStates.value[index].showSpelling =
      globalDisplayState.value.showSpelling
  })
}

// 全局切换词义显示
function toggleGlobalMeaning() {
  globalDisplayState.value.showMeaning = !globalDisplayState.value.showMeaning
  Object.keys(wordDisplayStates.value).forEach((key) => {
    const index = parseInt(key)
    wordDisplayStates.value[index].showMeaning =
      globalDisplayState.value.showMeaning
  })
}

// 监听单词列表变化，重新初始化显示状态
watch(
  () => localWordList.value.length,
  () => {
    initWordDisplayStates()
  },
)

// 初始化
async function init() {
  try {
    console.log('word-book 开始初始化')

    // 参考 word-training.vue 的初始化逻辑
    // 1. 先初始化 unitStore，这会设置 currentSeriesId 和 currentProgramId
    await unitStore.initUnitStore()
    console.log('word-book unitStore 初始化完成')

    // 2. 再初始化 programStore
    await programStore.initProgramStore()
    console.log('word-book programStore 初始化完成')

    // 3. 获取教材列表
    await fetchProgramList()

    // 4. 如果有选中的教材，获取单元列表和单词列表
    if (selectedProgramId.value) {
      await fetchUnitList()
      fetchWordList()
    }

    console.log('word-book 初始化完成')
  } catch (error) {
    console.error('word-book 初始化失败:', error)
    ElMessage.error('初始化应用数据失败，请稍后重试')
  }
}

onMounted(() => {
  init()
})
</script>

<style lang="scss" scoped>
.word-book {
  padding: 20px;
  height: 100%;
  background-color: var(--el-bg-color-page);

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .header-left {
      display: flex;
      align-items: center;
      gap: 20px;
    }

    .header-right {
      display: flex;
      align-items: center;
    }
  }

  &__title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  &__content {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
}

.word-table {
  .word-index {
    font-weight: 600;
    color: var(--el-color-primary);
  }

  .syllable-cell {
    display: flex;
    align-items: center;
    gap: 8px;

    .syllable-text {
      font-family: 'Times New Roman', serif;
      font-style: italic;
      color: var(--el-text-color-primary);
    }

    .play-button {
      font-size: 12px;
    }
  }

  .spelling-cell,
  .meaning-cell {
    position: relative;
    cursor: pointer;
    padding: 8px;
    border-radius: 4px;
    transition: background-color 0.2s;

    &:hover {
      background-color: var(--el-fill-color-light);
    }

    .toggle-button {
      position: absolute;
      top: 4px;
      right: 4px;
      font-size: 12px;
      opacity: 0;
      transition: opacity 0.2s;
    }

    &:hover .toggle-button {
      opacity: 1;
    }
  }

  .spelling-text {
    font-weight: 600;
    font-size: 16px;
    color: var(--el-text-color-primary);
  }

  .spelling-hidden,
  .meaning-hidden {
    color: var(--el-text-color-placeholder);
    font-style: italic;
  }

  .meaning-content {
    .meaning-text {
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }

    .example-text {
      font-size: 14px;

      .example-en {
        color: var(--el-text-color-regular);
        font-style: italic;
        margin-bottom: 4px;
      }

      .example-zh {
        color: var(--el-text-color-secondary);
      }
    }
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

// 表格行悬停效果
:deep(.el-table__row:hover) {
  .toggle-button {
    opacity: 1 !important;
  }
}
</style>
